

var tunningPanel;


/**
 * isRefreshTunningState = false means donot refresh TunningSQLNumber
 * 
 * if isRefreshTunningState = false and user click tunning SQL button
 * we will set isRefreshTunningState = true and send interval ajax request
 * and when query TunningSQLNumber we will use this panel key
 */
var isRefreshTunningState = false;


var getTabValue = function() {
	var tunningSQLScopes = Ext.getCmp('tunningSQLScope').getChecked();
	if(tunningSQLScopes) {
		var params = new Object();
		params.tunningSQLScope = tunningSQLScopes[0].getSubmitValue();
		return params;
	}
};


/**
 * When change tab call this method
 * 
 * 	About param notLoading 
 * 	When click top and down button or do some user feedback
 * 	We transfer true
 * 
 *  Default is undefined means loading window 
 */
var reloadTunningStore = function(notLoading) {
	var params = tunningPanel.getTabValue();
	if(notLoading === undefined) {
		Ext.getBody().mask('正在获取诊断SQL列表');
	}
	
	ajax({
		url:tunningBaseUrl + 'tunningSQLList.do',
		onlyUrl: true,
		params:{
			dbName:nowDBName,
			panelKey:getPaneKey(),
			tunningSQLScope:params.tunningSQLScope
		},
		success:function(resp) {
			Ext.getBody().unmask();
			var json = jsonDecode(resp.responseText);
			if(json.success) {
				tunningPanel.tunningDataStore.loadData(json.root.data);
				$('.shorten_text_class').shorten({"showChars" : 100, "moreText": "更多", "lessText": "收起"});
			}else {
				Ext.Msg.alert('提示' , json.root);
			}
		},
		failure:function(resp) {Ext.getBody().unmask();Ext.Msg.alert('提示' , resp.responseText);}
	});
}




//Tuning sql begin

var getSQL = function() {
	var tunningSQL = Ext.getCmp("tx_sql").getValue();
	var result = new Object();
    var selectSql = Ext.getCmp("tx_sql").editor.getSelection();
    if (selectSql != '') {
    	tunningSQL = selectSql;
    }
    if(Ext.isEmpty(tunningSQL)) {
		result.invaliaSQL = true;
		result.errorMessage = '您选择的行，SQL不能为空！';
	} else {
		result.tunningSQL = tunningSQL.htmlDecode();
	}
    return result;
}


var tunningSQL = function(moduleName) {
	var getSQLReturn = getSQL();
	if(getSQLReturn && (getSQLReturn.invalidRecordNumber === true || getSQLReturn.invaliaSQL === true)) {
		Ext.MessageBox.alert('提示', getSQLReturn.errorMessage);
		return;
	}
	var sqlText = getSQLReturn.tunningSQL;
	Ext.getBody().mask('正在拆分SQL语句...');
    ajax({
        url:getRoot() + '/websql/splitSQL',
        params:{"sqlText":sqlText},
        success:function(resp) {
            Ext.getBody().unmask();
            var json = jsonDecode(resp.responseText);
            if(json.success) {
                var sqlArray  = json.root;
                var timeDelay = json.timeDelay;
                
                // reset Tab result
                clearTabPanelResult();
                clearMsgPanelContent();
                tunningPanel = createTunningPanel();
                tunningTabPanel = {title:'优化列表', itemId:'tunningTabPanel', layout:'fit', items :[tunningPanel]};
                resultTabPanel.add(tunningTabPanel);
                trySetTabPanelToResult();
                
                addMsgPanelContent('\n\n【拆分SQL完成】：将执行SQL语句数量：（' + sqlArray.length + "条），拆分SQL耗时：（" + timeDelay + "ms.）");
                tunningSQLDoing(sqlArray, 0, moduleName);
            }else {
                Ext.Msg.alert('提示' , json.root);
            }
        },
        failure:function(resp) {
            Ext.getBody().unmask();
            Ext.Msg.alert('提示' , resp.responseText);
        }
    });
}


var tunningSQLDoing = function(sqlArray, index, moduleName) {
	if(index >= sqlArray.length) {
		// Guide user to tunning SQL List
		Ext.Msg.show({
			title:'提示',
			msg: '诊断任务添加成功, 到优化列表中查看?',
			minHeight:100,
			minWidth:250,
			buttons: Ext.Msg.YESNO,
			fn:function(option) {
				if('yes' == option) {
					redirectTunningList();
				}else {
					
				}
			}
		});
		return ;
	}
	
	var sql = sqlArray[index];
	var realSQL = sql ? sql.htmlDecode() : "";
	Ext.getBody().mask('正在优化SQL : ' + sql);
	ajax({
		url:tunningBaseUrl + 'tunningSQL.do',
		onlyUrl: true,
		timeout: 900000,
		params:{
			sqlText:realSQL,
			dbName:nowDBName,
			panelKey:getPaneKey(),
			moduleName:moduleName
		},
		success:function(resp) {
			Ext.getBody().unmask();
			var json = jsonDecode(resp.responseText);
			if(json.success) {
				if(json.root.message) {
					addMsgPanelContent("【优化SQL：(" + (index + 1) + ")】\n\n<span style='font-size: 12px;font-weight: bold;'>" + sql + "</span>\n\n" + '优化任务添加成功。');
					
					if(sqlArray.length == 1) {
						/**
						 * If task add successfully 
						 * We will show the index advice in limit time
						 * We will request for server database in limit request times
						 * In order to show result synchronizing
						 */
						var requestTimes = 0;
						var messageID = json.root.messageID;
						queryTunningSQLDetail(messageID, requestTimes);
					} else {
						tunningSQLDoing(sqlArray, index + 1, moduleName);
					}
				} else {
					Ext.MessageBox.alert('提示', '诊断任务添加失败，请稍后再试！');
				}
			}else {
             var errorMsg = json.root;
             addMsgPanelContent("【优化SQL：(" + (index + 1) + ")】\n\n<span style='font-size: 12px;font-weight: bold;'>" + sql + "</span>\n\n" + errorMsg);
             
             Ext.Msg.show({
                 title:'执行出错',
                 msg:Ext.util.Format.htmlDecode(errorMsg),
                 buttons:Ext.Msg.OK,
                 icon:Ext.Msg.ERROR
             });
			}
		},
		failure:function(resp) {
			Ext.getBody().unmask();
			addMsgPanelContent("【优化SQL：(" + (index + 1) + ")】\n\n<span style='font-size: 12px;font-weight: bold;'>" + sql + "</span>\n\n" + resp.responseText);
			Ext.Msg.alert('提示' , resp.responseText);
		}
	});
}


var queryTunningSQLDetail = function(messageID, requestTimes) {
	// Max Sync time = MAX_REQUEST_TIMES * REQUEST_INTEVAL;
	var MAX_QUERY_TUNNING_TIMES = 8;
	var QUERY_TUNNING_REQUEST_INTEVAL = 2;
	
	Ext.getBody().mask('正在获取SQL诊断结果');
	requestTimes = requestTimes + 1;
	ajax({
		url:tunningBaseUrl + 'tunningSQLList.do',
		timeout: 900000,
		onlyUrl: true,
		params:{
			dbName:nowDBName,
			panelKey:getPaneKey(),
			tunningSQLScope:"sql",
			messageID:messageID
		},
		success:function(resp) {
			Ext.getBody().unmask();
			var json = jsonDecode(resp.responseText);
			if(json.success) {
				/**
				 * If the sql task has no error code 
				 * It means not finished the sql tunning task
				 */
				if(json.root.data.length > 0) {
					showTunningSQLResult(json.root.data[0]);
					return ;
				}
					

				if(requestTimes <= MAX_QUERY_TUNNING_TIMES) {
					// Sleep QUERY_TUNNING_REQUEST_INTEVAL and repeated request
					Ext.getBody().mask('正在获取SQL诊断结果');
					var querySQLDetailTask = new Ext.util.DelayedTask(function(){
						Ext.getBody().unmask();
						queryTunningSQLDetail(messageID, requestTimes);
            		});
					querySQLDetailTask.delay(QUERY_TUNNING_REQUEST_INTEVAL * 1000);
				} else {
					// Guide user to tunning SQL List
					Ext.Msg.show({
						title:'提示',
						msg: '诊断任务添加成功, 到优化列表中查看?',
						minHeight:100,
						minWidth:250,
						buttons: Ext.Msg.YESNO,
						fn:function(option) {
							if('yes' == option) {
								redirectTunningList();
							}else {
								
							}
						}
					});
				}
			}else {
				Ext.Msg.alert('提示' , json.root);
			}
		},
		failure:function(resp) {
			Ext.getBody().unmask();
			Ext.Msg.alert('提示' , resp.responseText);
		}
	});
}


var redirectTunningList = function() {
	// refresh tunning title
	refreshTunningState();
	
	// change active tab
	trySetTabPanelToResult();
	reloadTunningStore();
}
// Tuning sql end



//
////Show tunning Result begin
///**
// * When click "诊断结果" or "反馈状态"
// * Call this method
// */
//var showSelectedTunningResult = function(option) {
//	var selectedRecord = tunningPanel.tunningDataPanel.getSelectionModel().getSelection()[0];
//	tunningPanel.tunningResultData = selectedRecord.data;
//	
//	// record click event to database
//	Ext.getBody().mask('正在获取诊断SQL列表');
//	ajax({
//		url:tunningBaseUrl + 'saveQueryTunningEvent.do',
//		onlyUrl: true,
//		params:{
//			option:option,
//			dbName:nowDBName,
//			panelKey:getPaneKey(),
//			messageID:selectedRecord.data.messageID
//		},
//		success:function(resp) {
//			Ext.getBody().unmask();
//			showTunningResult(selectedRecord.data);
//		},
//		failure:function(resp) {Ext.getBody().unmask();Ext.Msg.alert('提示' , resp.responseText);}
//	});
//	
//};
//
//
//var showTunningResult = function(data) {
//	
//	/**
//	 * Comment the code
//	 * If data.errorCode == RIGHT_NO_ADVICE
//	 * App server will add a '无诊断建议' in adviceList
//	 */
////	if(data.errorCode == RIGHT_NO_ADVICE) {
////		Ext.Msg.alert('提示' , '无诊断建议');
////		return ;
////	}
//	
//	/**
//	 * We must consider the following state
//	 * RIGHT_NO_ADVICE, AFFAIR_RIGHT, TUNNING_NOW, ERROR_STATE 
//	 * 
//	 * AFFAIR_RIGHT is ignored
//	 * RIGHT_NO_ADVICE is considered above
//	 * TUNNING_NOW has no link and cannot come in this method
//	 * SO we just need to consider ERROR_STATE
//	 */
//	if(data.errorCode != AFFAIR_RIGHT && data.errorCode != RIGHT_NO_ADVICE) {
//		Ext.Msg.alert('提示' , data.errorMessage);
//		return ;
//	}
//	
//	if(data) {
//		var adviceWindow = Ext.create('Ext.window.Window', {
//  	    title: '诊断结果',
//  	    height: 520,
//  	    width: 800,
//  	    modal:true,
//  	    id:'tunningAdviceWindow',
//  	    x:150,
//  	    y:10,
//  	    layout : 'fit',
//  	    closable : true,
//  	    buttonAlign:'center',
//  	    autoScroll:true,
//  	    items : [{
//  	        xtype : "component",
//  	        border: false,
//  	        autoEl : {
//  	            tag : "iframe",
//  	            src : "/mysql" + tunningBaseUrl +  "tunningResultPage.do?token=" + getUserToken()
//  	        }
//  	    }],
//  	    listeners: {
//  	    	 close:{
//  	    		 fn:function( panel, eOpts ) {
//  	    			 closeWindow();
//  	    		 }
//  	    	 }
//  	    }
//  	});
//		adviceWindow.show();
//	} else {
//		Ext.Msg.alert('提示' , '诊断结果数据异常，不能查看！');
//	}
//	
//};

/**
 * When click "优化" button
 * If the tunnning has result in the limit time or
 * If user click adivce or feedback link in tunning SQL list
 *
 * Call this method
 */
var showTunningSQLResult = function(data) {
	tunningPanel.tunningResultData = data;
	reloadTunningStore(true);
	showTunningResult(data);
};
// show tunning result end


var createTunningPanel = function() {
	var tunningStore = new Ext.data.Store({
		 model: 'TunningTaskDetail',
	     proxy: {
	         type: 'memory'
	     }
	});
	
	var tunningDataPanel = Ext.create('Ext.grid.Panel', {
	    store:tunningStore,
	    region:'center',
	    deferRowRender:false,
	    viewConfig:{ stripeRows:true, enableTextSelection:true},
	    columns:[ Ext.create('Ext.grid.RowNumberer', {width:40}),
	        {text:"SQL内容", dataIndex:"orginSQL", width:400,sortable:false, renderer:function(v) {
	        	if(v) return "<div class='shorten_text_class'>" + v + "</div>";
	        }},
	        {text:"诊断开始时间", dataIndex:"gmtCreated", width:160, sortable:false},
	        {text:"诊断结果", dataIndex:"errorCode", width:110,sortable:false, align:'center',renderer:function(v, metaData, record, rowIndex, colIndex) {
	        	var tunningMessage ;
	        	if(AFFAIR_RIGHT == v) {
	        		tunningMessage = '待优化';
	        	} else if(RIGHT_NO_ADVICE == v) {
	        		tunningMessage = '无建议';
	        	} else if(!v) { 
	        		return '正在诊断';
	        	} else {
	        		tunningMessage = '诊断失败';
	        	}
	        	
	        	var option = CLICK_TUNNING_RESULT;
	        	return '<a href="javascript:tunningPanel.showSelectedTunningResult(\'' + option + '\')">' + tunningMessage  + '</a>';
            }},
            {text:"反馈状态", dataIndex:"feedbackState", width:110,sortable:false, align:'center', renderer:function(v, metaData, record, rowIndex, colIndex){
            	var feedbackState;
            	if(!v) {
            		feedbackState = '未反馈'; 
            		if(!record.data.errorCode) {
            			return feedbackState;
            		}
            	} else if(v == 1) {
            		feedbackState = '已反馈';
            	} else if(v == 2) {
            		feedbackState = 'DMS处理中'
            	} else if(v == 3) {
            		feedbackState = 'DMS已回复'
            	}
            	var option = CLICK_FEEDBACK_STATE;
            	return '<a href="javascript:tunningPanel.showSelectedTunningResult(\'' + option + '\')">' + feedbackState + '</a>';
            }}
	    ]
	});
	

	var headerPanel = Ext.create('Ext.panel.Panel', {
		layout: {
	        type: 'hbox',
	        align: 'top'    
	    },
	    width:900,
	    height:40,
	    items: [{
	    	xtype:'radiogroup',
	    	id:'tunningSQLScope',
            itemId:'tunningSQLScope',
            width:400,
	        items:[
	            {name:'tunningSQLScope',inputValue:"panel",boxLabel:'当前页面诊断列表',checked:true},
	            {name:'tunningSQLScope',inputValue:"all",boxLabel:'历史所有诊断列表'}
	        ],
	        style: {
	        	marginTop:'7px'
	        },
	        listeners:{
	        	change:function(thiz, newValue, oldValue, eOpts) {reloadTunningStore()}
	        }
  		},{
  			xtype:'button',
  			text: '<span style="font-weight: bold;color:black">刷新</span>',
  			iconCls:'fa fa-refresh',
  			height:23,
  			width:60,
  			style: {
  				marginTop:'7px',
  				marginLeft:'15px',
  				background:'#F0F0F0',
  				'border-color':'#F0F0F0'
  			},
  			listeners:{
 	        	click:function(thiz, e, eOpts) {reloadTunningStore()}
 	        }
  		},{
  			xtype:'button',
  			text: '<span style="font-weight: bold;color:black">例子说明</span>',
  			height:23,
  			width:70,
  			style: {
  				marginTop:'7px',
  				marginLeft:'30px',
  				background:'#F0F0F0',
  				'border-color':'#F0F0F0'
  			},
  			listeners:{
 	        	click:function(thiz, e, eOpts) {showTunningDesc()}
 	        }
  		}]
		
	});
	
	var tunningPanel = Ext.create('Ext.panel.Panel', {
		// Properties
		tunningDataStore:tunningStore,
		tunningResultData:null, 
		tunningDataPanel:tunningDataPanel,
		
		// Methods
		getTabValue:getTabValue,
		showSelectedTunningResult:showSelectedTunningResult,
		showTunningSQLResult:showTunningSQLResult,
		
		autoScroll:true,
	    items: [headerPanel,tunningDataPanel]
	});
	return tunningPanel;
};

//Refresh tab title's tunning sql number
var refreshTunningState = function() {
	
	var refreshRequest = function() {
		ajax({
	        url:tunningBaseUrl + 'refreshTunningState.do',
	        onlyUrl: true,
	        params:{
	        	dbName:nowDBName,
	        	panelKey:getPaneKey()
	        },
	        success:function(resp) {
	            var json = jsonDecode(resp.responseText);
	            if(json.success) {
	            	// interval ajax request
	            	if(json.root.tunningNumber > 0) {
	            		// set tab title
	            		resultTabPanel.getComponent('tunningTabPanel').setTitle('优化列表[' + json.root.tunningNumber + ']');
	            		
	            		var refreshTask = new Ext.util.DelayedTask(function(){
	            			refreshRequest();
	            		});
	            		refreshTask.delay(3 * 1000);
	            	} else {
	            		// all sql tunning finish
	            		isRefreshTunningState = false;
	            		
	            		// set tab title
	            		resultTabPanel.getComponent('tunningTabPanel').setTitle('优化列表');
	            		
	            		// reload data
	            		reloadTunningStore();
	            		
	            	}
	            }
	        },
	        failure:function(resp) {
	        	// error reset the state
	        	isRefreshTunningState = false;
	        }
	    });
	}
	
	if(isRefreshTunningState == false) {
		 isRefreshTunningState = true;
		 /**
		  * When refreshRequest() method finish 
		  *	We must reset isRefreshTunningState = false
		  * in order to be used by the following tunning service
		  */
		 refreshRequest();
	}
}


